<template>
    <div class="content">
        <van-form colon @submit="onSubmit" validate-first @failed="onFailed">
            <div class="title">人员基本信息</div>
            <van-field
                    v-model="formItem.name"
                    name="name"
                    label="姓名"
                    placeholder="请填写真实姓名"
                    :maxlength="20"
                    @focus="bodyScrollTop"
                    @blur="bodyScrollTop"
                    :rules="[{ validator: nameValidator,required: true, message: '请输入姓名' }]"></van-field>
            <van-field
                    v-model="formItem.relation"
                    name="relation"
                    label="代办关系"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="请填写代办关系"></van-field>
            <van-field
                    readonly
                    clickable
                    name="area"
                    :value="card_type_text"
                    label="证件类型"
                    placeholder="点击选择证件类型"
                    @click="showCardType = true"
            />
            <van-popup v-model="showCardType" position="bottom">
                <van-picker show-toolbar
                            title="证件类型"
                            @cancel="showCardType=false"
                            @confirm="onSyAreaConfirm"
                            :columns="cardTypeList"/>
            </van-popup>
            <van-field
                    v-if="card_type_text === '身份证'"
                    v-model="formItem.card_no"
                    name="card_no"
                    label="身份证号"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="请填写真实身份证号"
                    :rules="[{ validator: idCardValidator, message: '身份证号格式有误' }]"
            />
            <van-field
                    v-else
                    v-model="formItem.card_no"
                    name="card_no"
                    label="通行证号"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="请填写8位通行证号"
            />
            <van-field
                    v-model="formItem.other_card_no"
                    v-if="card_type_text === '港澳居民通行证/居民居住证'"
                    label="居住证号"
                    placeholder="请填写18位居民居住证号"
            />
            <van-field
                    v-model="formItem.other_card_no"
                    v-if="card_type_text === '台湾居民通行证/居民居住证'"
                    label="居住证号"
                    placeholder="请填写18位居民居住证号"
            />
            <van-field v-model="formItem.tel" name="tel" label="手机号" :rules="phoneRules" placeholder="请填写真实手机号"
                       @focus="bodyScrollTop" @blur="bodyScrollTop"/>
            <area-page ref="areaPage" @result="bodyScrollTop"></area-page>
            <div class="title">近期情况</div>
            <recent-situation ref="recentSituation" @result="bodyScrollTop"></recent-situation>

            <div class="div-bot">
                <van-button :disabled="submitDisabled" :loading="submitLoading" round block type="info"
                            native-type="submit" class="city-card-common-btn">
                    提交
                </van-button>
            </div>
        </van-form>
        <!-- 公众号二维码-->
        <van-popup v-model="successModel" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="success-title">
                <div>长 按 识 别 关 注 公 众 号</div>
                <div>查 看 通 行 证</div>
            </div>
            <div class="success-code">
                <img :src="require('@/assets/images/sst-qrcode-mz.png')"/>
            </div>
        </van-popup>
        <!--    提示说明    -->
        <van-popup v-model="showReadme" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="readme-popup">
                <div class="readme-popup-title">温馨提示</div>
                <div class="readme-popup-content">
                    <p>根据《中华人民共和国传染病防治法》和沈阳市新型冠状病毒感染的肺炎疫情防控指挥部相关通告，本地、外来入沈人员应主动申领“健康通行码”，作为个人在沈通行的电子凭证。</p>
                    <p>本次“健康通行码”申领将纳入个人征信评价，请您主动办理，如实填报各项信息。</p>
                    <p>感谢您对沈阳市疫情防控工作的支持配合！</p>
                    <div class="tong-yi-box">
                        <van-checkbox v-model="tongyi" style="float: left;margin: 0px 8px;"></van-checkbox>
                        <div>
                            本人主动申领“健康通行码”，自愿填报各项个人信息，并承诺填报信息真实准确。如有虚假，本人愿承担相关法律责任。
                        </div>
                    </div>
                </div>
                <div class="readme-popup-btn">
                    <van-button block type="info"
                                native-type="button"
                                size="small"
                                class="readme-popup-btn-sm"
                                @click="choose">
                        申领办理
                    </van-button>
                </div>
            </div>

        </van-popup>

    </div>
</template>

<script>
import { insertNewPermitPerson, insertNewPermitChildren, getOpenidMsg, getByCardNo } from '@/api/yi-qing-fang-kong.js'
// 工具
import { Dialog } from 'vant'
import { identityCodeValid, identityMobile } from '@/libs/tools'
import AreaPage from './components/area-page/index'
import RecentSituation from './components/recent-situation/index'
import wx from 'weixin-js-sdk'

export default {
  components: {
    RecentSituation,
    AreaPage
  },
  data () {
    this.phoneRules = [
      { required: true, message: '请输入手机号' },
      { validator: this.phoneValidator, message: '手机号格式错误' }
    ]
    return {
      addType: '',
      relation: '',
      cardTypeList: [
        { text: '身份证', id: '1' },
        { text: '港澳居民通行证/居民居住证', id: '5' },
        { text: '台湾居民通行证/居民居住证', id: '4' }
      ],
      mine_card_no: '',
      formItem: {
        // 表单数据
        name: '',
        card_no: '',
        tel: '',
        card_type: '',
        area_type: '', // 区域类型
        area_id: '',
        street_id: '',
        community_id: '',
        area: '',
        street: '',
        community: '',
        loc_province: '', // 地图选取后的省
        loc_city: '', // 地图选取后的市
        loc_title: '', // 地图选取后的地址名
        loc_address: '', // 地图选取后的具体地址
        house_num: '', // 门牌号
        is_hubei: '',
        is_contact: '',
        health_state: '',
        temp: ''
      },
      sendBtnType: false,
      showReadme: true,
      tongyi: true,
      submitDisabled: false,
      submitLoading: false,
      successModel: false,
      showCardType: false,
      card_type_text: '',
      routeObj: {} // 路由对象
    }
  },
  computed: {},
  methods: {
    onSyAreaConfirm (value, index) {
      console.log(value)
      this.showCardType = false
      this.formItem.card_type = value.id
      this.card_type_text = value.text
    },
    failNotice (title) {
      this.$notify({ type: 'danger', message: title })
    },
    idCardValidator (val) {
      // 身份证
      const reg1 = identityCodeValid(val)
      if (!reg1.pass) {
        // this.failNotice('请检查身份证格式！')
        return false
      }
    },
    phoneValidator (val) {
      return identityMobile(val)
    },
    nameValidator (val) {
      if (val === '') {
        this.failNotice('请输入姓名')
        return false
      }
      return true
    },
    cardTypeValidator (val) {
      if (val === '') {
        this.failNotice('请选择证件类型')
        return false
      }
      return true
    },
    onFailed (errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
      console.log('failed', errorInfo)
    },
    onSubmit (value) {
      console.log('表单提交', this.formItem)
      // 校验姓名
      if (!this.formItem.name) {
        this.failNotice('请输入姓名')
        return false
      }
      // 代办关系
      if (!this.formItem.relation) {
        this.failNotice('请输入代办关系')
        return false
      }

      // 证件类型
      if (this.card_type_text === '') {
        this.failNotice('请选择证件类型')
        return false
      }
      // 校验证件号
      if (!this.formItem.card_no) {
        this.failNotice('请输入证件号码')
        return false
      } else {
        if (this.formItem.card_type === '1') {
          const rtn = identityCodeValid(this.formItem.card_no)
          // console.log('身份证校验原因', rtn.tip)
          // console.log('身份证校验状态', rtn.pass)
          if (!rtn.pass) {
            this.failNotice(rtn.tip)
            return false
          }
        }
      }
      // 校验手机号
      if (!identityMobile(this.formItem.tel)) {
        this.failNotice('请输入正确手机号')
        return false
      }
      // 区域部分
      const areaPageData = this.$refs.areaPage.checkForm()

      // 近期情况
      const recentSituationData = this.$refs.recentSituation.checkForm()

      // 姓名去空格处理
      this.formItem.name = this.formItem.name.toString().replace(/\s/ig, '')
      // 手机号去空格处理
      this.formItem.tel = this.formItem.tel.toString().trim()
      // 身份证去空格处理
      this.formItem.card_no = this.formItem.card_no.toString().trim()
      if (this.formItem.tel.length !== 11) {
        this.failNotice('请输入正确手机号')
        return false
      } else {
        console.log(this.formItem.tel, '手机位数为：' + this.formItem.tel.length)
      }

      console.log('区域组件', areaPageData)
      console.log('近期情况组件', recentSituationData)
      if (areaPageData && recentSituationData) {
        // 组件数据处理
        this.formItem.area_type = areaPageData.area_type
        this.formItem.area_id = areaPageData.area.id
        this.formItem.area = areaPageData.area.text
        this.formItem.street_id = areaPageData.street.id
        this.formItem.street = areaPageData.street.text
        this.formItem.community_id = areaPageData.community.id
        this.formItem.company_code = !this.$common.xeUtils.isEmpty(areaPageData.community.company_code) ? areaPageData.community.company_code : areaPageData.street.company_code
        this.formItem.community = areaPageData.area_type === '1' ? areaPageData.community.text : areaPageData.cunValue
        this.formItem.house_num = areaPageData.house_num
        this.formItem.loc_title = areaPageData.title
        this.formItem.loc_address = areaPageData.address
        this.formItem.loc_province = areaPageData.province
        this.formItem.loc_city = areaPageData.city
        this.formItem.longitude = areaPageData.lng
        this.formItem.latitude = areaPageData.lat
        this.formItem.address = this.formItem.loc_province + this.formItem.loc_city + this.formItem.loc_title + this.formItem.loc_address
        this.formItem.is_hubei = recentSituationData.is_hubei
        this.formItem.is_contact = recentSituationData.is_contact
        this.formItem.health_state = recentSituationData.health_state_copy.join('^')
        this.formItem.health_state.replace(/,/g, '^')
        this.formItem.temp = recentSituationData.temp
        this.formItem.stay_city = recentSituationData.stay_city
        // this.formItem.cardno = this.formItem.card_no
        // this.formItem.card_no2 = this.formItem.card_no
        // this.formItem.card_no = this.mine_card_no
        if (this.addType === '0') {
          this.formItem.p1 = 'children'
        }
        if (this.addType === '1') {
          this.formItem.p1 = 'person'
        }
        // 校验成功后插入
        console.log('校验成功-进开始行插入', this.formItem)

        if (this.formItem.is_contact.toString() === '1') {
          Dialog.alert({
            title: '温馨提示',
            message: '<span style="color:red;">请再次确认近14天您是否接触新冠肺炎确诊病例或疑似病例？</span>'
          }).then(() => {
            this.insertUserpermitAction()
            // on close
          })
        } else {
          this.insertUserpermitAction()
        }
      }
    },
    // 表单提交
    insertUserpermitAction () {
      console.log('表单最终提交内容', this.formItem)
      // 表单提交
      this.successModel = false
      this.submitDisabled = false
      this.submitLoading = true
      if (this.addType === '0') {
        insertNewPermitChildren(this.formItem).then(ret => {
          if (ret.data.errcode === 0) {
            this.submitDisabled = true
            this.submitLoading = false
            console.log('保存回调', ret.data.data)
            window.localStorage.removeItem('formData')
            if (this.$route.query.selfTs === 'selfTs') {
              this.$dialog.alert({
                title: '温馨提示',
                message: '感谢您的支持配合,您的申请信息已经成功提交,比对验证结果稍后将通过微信公众号向您推送!'
              }).then(() => {
                this.$common.wxCallBack(function () {
                  wx.closeWindow()
                })
              })
            } else {
              this.$dialog.alert({
                title: '温馨提示',
                message: '添加成功！'
              }).then(() => {
                this.$router.push({
                  name: 'epidemic-newly-added'
                })
              })
              // this.successModel = true
            }
          } else {
            this.successModel = false
            this.submitDisabled = false
            this.submitLoading = false
            let msg = ''
            if (ret.data.sid) {
              msg = ret.data.errmsg + '/sid:/' + ret.data.sid
            } else {
              msg = ret.data.errmsg
            }
            this.failNotice(msg)
          }
        })
      } else if (this.addType === '1') {
        insertNewPermitPerson(this.formItem).then(ret => {
          if (ret.data.errcode === 0) {
            this.submitDisabled = true
            this.submitLoading = false
            console.log('保存回调', ret.data.data)
            window.localStorage.removeItem('formData')
            if (this.$route.query.selfTs === 'selfTs') {
              this.$dialog.alert({
                title: '温馨提示',
                message: '感谢您的支持配合,您的申请信息已经成功提交,比对验证结果稍后将通过微信公众号向您推送!'
              }).then(() => {
                this.$common.wxCallBack(function () {
                  wx.closeWindow()
                })
              })
            } else {
              this.$dialog.alert({
                title: '温馨提示',
                message: '添加成功！'
              }).then(() => {
                this.$router.push({
                  name: 'epidemic-newly-added'
                })
              })
              // this.successModel = true
            }
          } else {
            this.successModel = false
            this.submitDisabled = false
            this.submitLoading = false
            let msg = ''
            if (ret.data.sid) {
              msg = ret.data.errmsg + '/sid:/' + ret.data.sid
            } else {
              msg = ret.data.errmsg
            }
            this.failNotice(msg)
          }
        })
      } else {
        this.$dialog.alert({
          title: '温馨提示',
          message: '操作有误，请重新申请代办'
        }).then(() => {
          this.$common.wxCallBack(function () {
            wx.closeWindow()
          })
        })
      }
    },
    getByCardNoAciton (data) {
      getByCardNo({ cardno: data }).then(ret => {
        if (ret.data.errcode === 0) {
          // this.formItem = ret.data.data
          // console.log(ret.data.data, '11111')
          // console.log(this.formItem, '2222')
          // if (!this.$common.xeUtils.isEmpty(ret.data.data.result)) {
          // this.successModel = true
          // this.$router.push({
          //   name: 'epidemic-submit-success',
          //   query: {}
          // })
          // }
        } else {
          this.failNotice(ret.data.errmsg)
        }
      })
    },
    getOpenidInfoAction () {
      getOpenidMsg().then(ret => {
        console.log('判断是否注册过', ret.data)
        if (ret.data.errcode === 0) {
          this.mine_card_no = ret.data.data.result.card_no
          // if (!this.$common.xeUtils.isEmpty(ret.data.data.result)) {
          // this.successModel = true
          // this.$router.push({
          //   name: 'epidemic-submit-success',
          //   query: {}
          // })
          // }
        } else {
          // this.failNotice(ret.data.errmsg)
        }
      })
    },
    // 去苹果机型白边
    bodyScrollTop () {
      winToTop()
      this.setStorage(this.formItem)
    },
    setStorage (formData) {
      window.localStorage.setItem('formData', JSON.stringify(formData))
    },
    choose () {
      this.showReadme = !this.tongyi
    }

  },
  mounted () {
    // 获取路由信息
    this.routeObj = this.$route.query
    console.log('表单页面路由信息', this.routeObj)
    this.addType = this.$route.query.type
    if (this.addType === '0') {
      this.relation = '儿童代办'
    }
    if (this.addType === '1') {
      this.relation = '父母代办'
    }
    if (this.routeObj.cardno) {
      this.getByCardNoAciton(this.routeObj.cardno)
    }
    // 获取登录信息
    this.getOpenidInfoAction()
    // 获取本地表单数据
    // if (window.localStorage.getItem('formData')) {
    //   this.formItem = JSON.parse(window.localStorage.getItem('formData'))
    //   console.log('表单页面表单数据', this.formItem)
    //   window.localStorage.removeItem('formData')
    // }
    // 区域菜单数据预处理
    console.log('表单信息', this.formItem)
  },
  watch: {
    formItem () {
      console.log('表单变化啦')
    }
  }
}
</script>

<style scoped>
    /deep/ .van-field__label {
        min-width: 5.625rem;
        margin-right: 10px;
        width: auto;
    }

    .mobile-verify-code {
        display: flex;
        justify-content: center;
        padding: 15px;
    }

    .success-code {
        display: flex;
        justify-content: center;
        padding: 5px 15px 10px;
    }

    .success-title {
        padding: 5px;
        text-align: center;
    }

    .van-radio {
        float: left;
        margin-right: 10px;
    }

    .van-popup /deep/ .van-ellipsis {
        font-size: 0.95rem;
    }

    .title {
        width: 100%;
        padding: 0.625rem 0.9375rem;
        font-size: 12px;
    }

    .action-item .van-cell__title {
        -webkit-box-flex: inherit;
        -webkit-flex: inherit;
        flex: inherit;
        width: 5.625rem;
    }

    .content {
        width: 100%;
        background-color: #F5F5F5;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }

    .content >>> .van-cell {
        margin: 0 2%;
        width: 96%;
        font-size: 12px;
    }

    .content >>> .van-dialog__content {
        padding: 10px;
        text-align: center;
    }

    .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value .van-field__body .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value {
        text-align: left;
    }

    .div-bot {
        margin: 10px;
    }

    .div-bot >>> .van-button--info {
        border: 1px solid #75ACDC;
    }

    .div-bot >>> .van-button {
        height: 2.5rem;
    }

    .city-card-common-btn {
        color: white;
        font-size: 12px;
        padding: 0;
        width: 100%;
        border-radius: 5px;
        text-align: center;
        background-color: #75ACDC;
    }

    .content >>> .van-cell__value {
        /*flex: inherit;*/
        font-size: 12px;
    }

    .content >>> .value-item .van-cell__value {
        width: 100%;
    }

    .van-action-sheet__cancel, .van-action-sheet__item {
        font-size: 12px;
    }

    .van-cell__value span {
        /*color: black;*/
    }

    .van-dropdown-menu {
        height: 25px;
    }

    .van-hairline--top-bottom::after {
        border-width: 0px 0px;
    }

    .chaochu >>> .van-cell__value {
        width: 100%;
    }

    .div1 >>> .van-cell__value {
        width: 100%;
    }

    .div2 >>> .van-cell__value {
        width: 100%;
    }

    .other-info .van-field__label.radio-item, .tou .van-field__label.radio-item {
        width: 8.625rem;
    }

    .suggest.van-cell.van-field span {
        width: 5rem;
    }

    .readme-popup {
        padding: 25px;
    }

    .readme-popup .readme-popup-title {
        text-align: center;
        color: red;
        font-weight: bold;
        text-decoration: underline;
    }

    .readme-popup p {
        margin: 5px 0 5px 0;
        font-size: 12px;
        text-indent: 25px
    }

    .readme-popup-btn {
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }

    .readme-popup-btn-sm {
        width: 45%;
    }

    .tong-yi-box {
        font-size: 12px;
    }

    .tong-yi-box >>> .van-checkbox__icon {
        font-size: 15px;
    }

    /*.content >>> .van-button--small{*/
    /*    padding: 0;*/
    /*}*/
</style>
